package com.search.tools;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import java.io.UnsupportedEncodingException;

@Slf4j
public class CapitalSearch {

    private  static  String url = "https://obs.jiatu.cloud/obs/client/api/search/aggSearch";
    private  String entityStr = "{\"keyword\":\"12345\",\"pageNo\":1,\"pageSize\":12,\"publisher\":\"\",\"author\":\"\",\"subject\":\"\",\"classno\":\"\",\"days\":\"\",\"language\":\"\",\"pubdate\":\"\",\"holdingStatus\":0,\"matchType\":0,\"subLibcode\":\"\"}";

    private static JSONObject entity;


    static {
        entity = new JSONObject();

    }

    public static void main(String[] args) throws UnsupportedEncodingException {
        //post("url");
    }
    public boolean search(String isbn) throws UnsupportedEncodingException {

        JSONObject result = post(isbn);
        if(null!=result){
            int code = result.getInteger("code");
            boolean isSuccess = result.getBoolean("success");
            if(isSuccess && 0==code){
                JSONObject data = result.getJSONObject("data");
                if(null!=data){
                    int total = data.getInteger("total");
                    log.debug("搜索到数量"+total);
                    JSONArray jsonArray = data.getJSONArray("data");
                    if(null!=jsonArray && jsonArray.size()>0){
                        JSONObject book = (JSONObject) jsonArray.get(0);
                        int holding = book.getInteger("holding");
                        if(holding>0){
                            return true;
                        }else {
                            return false;
                        }

                    }
                }else{
                    return false;
                }
            }
        }else {
            return false;
        }



        return false;
    }

    public JSONObject post(String isbn) throws UnsupportedEncodingException {

        entityStr = entityStr.replace("12345",isbn);

        entity.put("keyword",isbn);
        entity.put("pageNo","1");
        entity.put("pageSize","12");
        entity.put("publisher","");
        entity.put("author","");
        entity.put("subject","");
        entity.put("classno","");
        entity.put("days","");
        entity.put("language","");
        entity.put("pubdate","");
        entity.put("holdingStatus","0");
        entity.put("matchType","0");
        entity.put("subLibcode","");
        HttpResponse response ;
        JSONObject result=null;
        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpPost post = new HttpPost(url);
        RequestConfig requestConfig = RequestConfig.custom()
                .setConnectTimeout(50000) // 连接超时时间，单位毫秒
                .setSocketTimeout(50000)  // 读取超时时间，单位毫秒
                .build();
        post.setConfig(requestConfig);
        post.setHeader("Host","obs.jiatu.cloud");
        post.setHeader("Connection","keep-alive");
        post.setHeader("clientinfo","{\"appid\":\"wx04b02a49ed8f0be3\",\"channel\":\"obs-wx-mini\",\"libcode\":\"STL50\",\"libType\":1}");
        post.setHeader("xweb_xhr","1");
        post.setHeader("jwt","eyJlbmMiOiJBMTI4R0NNIiwiYWxnIjoiUlNBLU9BRVAifQ.jUthzDel7llQbaByNeICu69iCQVX0Zzgj6yZxin1VOuBAOwSHTzg9w1vx70mZq5JDFdaaScU93kWIbR4i7wZddhLJCulqs2roaPdlaNNXdFgSwQZmsClAq7UR2YY3jbYdoBzj7h7CONXFf4Vu5oogdoifZSbxS6XTreR5X19sfo.O8LDC_tj_j9TOHxU.vJIDSl3VfUxA8TBpEpJBahXIOWw41Cf_ITTLwhsTy4TFg3BmTtl-Rrk5E2qKuE9c9D8BB2SAWCRuKpjSkrfVc6sHDIgJNxbyOtRzhqV9W4N4oIbeXS9FYMr6HRL-KjPW5c_CrtsZ51y9-v03C12TWwVEFIi0EwuNzLSYqfBit1YBY8BGYBSrI0SoraLqeQBBtUXKzLkuLpe-bzevKMMzku-zkprZxJOCDWNeCJvvZRH61EsjHYiCk-IhGB1M2V2ahNh3itfoC2H7SMJLp1B1kzeijHcpR5xQJ03PnB4Z98dfxz7wDbsHbSYS04jZ_G9g-OM3taSb7JYnoggHu8XlaXo37XRLLDP8r_89LTEtEHpTZLJeDVg1RGprh5Th71_kEY6tD8JwrNKw2HJ_IpW5irOsi5KACx3bJmQo-5RoJZNrbJi03pljhJcEap9fKuyjE_p6TsViCYPrWiqmKF-GaHqfeM7MKZ9b4euujO65mHRCwV7VT1PEF0vN.hknjlnUkQldlArnpCU7veQ");
        post.setHeader("X-Okapi-Tenant","");
        post.setHeader("User-Agent","Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/116.0.0.0 Safari/537.36 MicroMessenger/7.0.20.1781(0x6700143B) NetType/WIFI MiniProgramEnv/Windows WindowsWechat/WMPF WindowsWechat(0x63090b19)XWEB/9193");
        post.setHeader("obsBindId","");
        post.setHeader("Content-Type","application/json");
        post.setHeader("Accept","*/*");
        post.setHeader("Sec-Fetch-Site","cross-site");
        post.setHeader("Sec-Fetch-Mode","cors");
        post.setHeader("Sec-Fetch-Dest","empty");
        post.setHeader("Referer","https://servicewechat.com/wx04b02a49ed8f0be3/22/page-frame.html");
        post.setHeader("Accept-Encoding","gzip, deflate, br");
        post.setHeader("Accept-Language","zh-CN,zh;q=0.9");
        post.setHeader("Cache-Control","no-cache");

        String jsonString =entity.toString();
        StringEntity stringEntity = new StringEntity(jsonString);
        //stringEntity.setContentType("application/json");
        //post.setEntity(stringEntity);
        post.setEntity(new StringEntity(entityStr, ContentType.APPLICATION_JSON));


        try{
            response = httpclient.execute(post);
            String body = EntityUtils.toString(response.getEntity(), HTTP.UTF_8);
            result = JSONObject.parseObject(body);
            //System.out.println(result);

        }catch (Exception e){
            log.error("请求图书馆接口出错"+e.toString());
            e.printStackTrace();
        }


        return result;
    }


}
